/**
 * 
 */
package file;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.NonWritableChannelException;

/**
 * @author Divyesh
 *
 */
public class FileWriter 
{
	FileLock lock;
	String Path;
	String mode;
	public RandomAccessFile file;
	public FileWriter(String path, String mode) throws FileNotFoundException  
	{
		this.Path = path;
		this.mode = mode;
	}
		
	public RandomAccessFile fileOpen(boolean force)
	{	
		try 
		{
			while (true)
			{
				//Filepermission.setReadWrite(Path);
				
				//while (channel.isOpen() == false);
				try 
				{
					file = new RandomAccessFile(Path, mode);
					FileChannel channel = file.getChannel();
					channel.force(force);
					lock = channel.lock();
					break;
				}
				catch (NonWritableChannelException e1) 
				{
					System.out.println("file:FileWriter:fileOpen(force):Exception::"+e1.getMessage());
					//e1.printStackTrace();
				}
				catch (Exception e) 
				{
					System.out.println("file:FileWriter:fileOpen(force):Exception::"+e.getMessage());
					//e.printStackTrace();
					Thread.sleep(2000);
				}
			}			
		} 
		catch (Exception e) 
		{
			System.out.println("file:FileWriter:fileOpen(force):Exception::"+e.getMessage());
			//e.printStackTrace();
		}
		return file;
	}
	public RandomAccessFile fileOpen()
	{
		try 
		{
			while (true)
			{
				//Filepermission.setReadWrite(Path);
				file = new RandomAccessFile(Path, mode);
				//while (channel.isOpen() == false);
				try 
				{
					FileChannel channel = file.getChannel();
					lock = channel.lock();
					break;
				}
				catch (NonWritableChannelException e1) 
				{
					System.out.println("file:FileWriter:fileOpen():Exception::"+e1.getMessage());
					//e1.printStackTrace();
				}
				catch (Exception e) 
				{
					System.out.println("file:FileWriter:fileOpen():Exception::"+e.getMessage());
					//e.printStackTrace();
					Thread.sleep(2000);
				}
			}			
		} 
		catch (Exception e) 
		{
			System.out.println("file:FileWriter:fileOpen():Exception::"+e.getMessage());
			//e.printStackTrace();
		}
		return file;
	}

	public void fileClose()
	{
		try 
		{
			try 
			{
				lock.release();
			} catch (Exception e) {
			}
			file.close();
			//Filepermission.setReadOnly(Path);
		} 
		catch (IOException e) {
			System.out.println("file:FileWriter:fileClose():Exception::"+e.getMessage());
		}
	}	
}
